package com.masq.aboard.common.exceptions;

import com.masq.aboard.common.enums.ResultCode;
import com.masq.aboard.common.results.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author masq
 * @since 2024-05-02
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 处理Token相关异常
    @ExceptionHandler({TokenExpireException.class, NonTokenException.class, InvalidTokenException.class})
    public ResponseEntity<CommonResult<?>> tokenExceptionHandler(Exception e) {
        ResultCode resultCode;
        switch (e.getClass().getSimpleName()) {
            case "TokenExpireException":
                resultCode = ResultCode.TOKEN_EXPIRED;
                break;
            case "NonTokenException":
                resultCode = ResultCode.TOKEN_NOT_EXIST;
                break;
            case "InvalidTokenException":
                resultCode = ResultCode.TOKEN_ERROR;
                break;
            default:
                resultCode = ResultCode.UNKNOWN_ERROR;
                break;
        }
        CommonResult<?> failedResult = CommonResult.failed(resultCode);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(failedResult);
    }

    // 处理用户名或密码错误异常
    @ExceptionHandler({UsernameNotFoundException.class, BadCredentialsException.class})
    public ResponseEntity<CommonResult<?>> authenticationExceptionHandler(Exception e) {
        CommonResult<?> failedResult = CommonResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        // 对于生产环境，避免泄露详细错误信息
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(failedResult);
    }

    // 处理自定义基类异常
    @ExceptionHandler(BaseException.class)
    public ResponseEntity<CommonResult<?>> baseExceptionHandler(BaseException e) {
        // 使用更合适的状态码处理业务逻辑错误
        CommonResult<?> failedResult = CommonResult.failed(e.getCode(), e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(failedResult);
    }

    // 可以考虑添加对未捕获异常的处理
    @ExceptionHandler(Exception.class)
    public ResponseEntity<CommonResult<?>> unspecifiedExceptionHandler(Exception e) {
        // 记录日志，返回通用 CommonResult<?> failedResult = CommonResult.failed错误信息
        logger.error("系统发生未知错误：{}", e.getMessage(), e);
        CommonResult<?> failedResult = CommonResult.failed();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failedResult);
    }
}
